import { computed, reactive, Ref, ref } from 'vue'
import { TagTableState } from '../types'
import { Pagination } from '#/antd'
import { QueryTagReq, TagIsUse } from '@/api/premium/content/model/tagModel'
import { batchDeleteTag, fetchTagList, TagApi } from '@/api/premium/content/tag'
import { formatPagination } from '@/utils/antdOpFormatHelper'
import { useStore } from '@/store'
import { ClassifyItem } from '@/api/premium/category/model/classifyModel'
import { message } from 'ant-design-vue'

const useSearchTagList = (currentClassify: Ref<ClassifyItem>) => {
  const store = useStore()
  const currentCategory = ref<string[]>(['-1'])
  const tagSearchValue = ref<string>('')
  const pageInfo = ref<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const tagListTableState = reactive<TagTableState>({
    selectedRowKeys: [],
    tableSize: 'small',
    tableData: [],
    tableColumns: [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '标签',
        dataIndex: 'tagName',
      },
      {
        title: '修改人',
        dataIndex: 'modifyUser',
      },
      {
        title: '修改时间',
        dataIndex: 'updateTime',
      },
      {
        title: '创建人',
        dataIndex: 'addUser',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '操作',
        dataIndex: 'options',
        width: 50,
        slots: {
          customRender: 'options',
        },
      },
    ],
  })

  const queryTagList = async () => {
    const reqData: QueryTagReq = {
      current: pageInfo.value.current,
      size: pageInfo.value.pageSize,
    }
    if (currentCategory.value[0] === '-1') {
      reqData.isUse = TagIsUse.NOUSE
      reqData.tagName = tagSearchValue.value
    } else {
      reqData.isUse = TagIsUse.USE
      reqData.tagName = tagSearchValue.value
      reqData.categoryId = currentCategory.value[0]
    }
    const { data } = await fetchTagList(reqData)
    pageInfo.value = formatPagination(data)
    tagListTableState.tableData = data.records
  }
  const fetchTagListLoading = computed(() =>
    store.getters['global/isOpLoading'](TagApi.QUERY_TAG_LIST)
  )

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const selectTreeNode = async (...args: any[]) => {
    const e = args[1]
    currentClassify.value = e.selectedNodes[0].props.dataRef
    await queryTagList()
  }

  const delTags = async (ids: string[]) => {
    await batchDeleteTag(ids)
    message.success('标签删除成功！')
    await queryTagList()
  }
  const batchDeleteTagLoading = computed(() =>
    store.getters['global/isOpLoading'](TagApi.BATCH_DELETE_TAG)
  )

  const formatTotalPageText = (total: number) => `共 ${total} 个`

  return {
    currentCategory,
    tagListTableState,
    queryTagList,
    fetchTagListLoading,
    tagSearchValue,
    pageInfo,
    formatTotalPageText,
    selectTreeNode,
    delTags,
    batchDeleteTagLoading,
  }
}

export default useSearchTagList
